package com.tsp_tux.demo.Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @author 张志豪
 */
@Component
public class SendEmail {

    @Value("${spring.mail.username}")
    private String from; //发件人
    private static int verifyCodeFigure;

    @Value("${VerifyCodeFigure}")
    public void setVerifyCodeFigure(int v) {
        verifyCodeFigure = v;
    }


    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送html格式邮件
     *
     * @param map 必修包含收件人(mailto)、主题(subject)、内容(content)三部分，内容可以是html格式
     * @author 张志豪
     */
    public void sendEmail(Map<String, String> map) {
        String mailto = String.valueOf(map.get("mailto"));
        String subject = String.valueOf(map.get("subject"));
        String content = String.valueOf(map.get("content"));

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //设置发件人
            mimeMessageHelper.setFrom(from);
            //设置收件人
            mimeMessageHelper.setTo(mailto);
            //设置邮件主题
            mimeMessageHelper.setSubject(subject);

            mimeMessageHelper.setText(content, true);

            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            System.out.println("发送邮件出现错误");
        }
    }

    /**
     * @return 验证码
     * @author 张志豪
     * 生成指定位数的验证码
     */
    public static String getVerifyCode() {
        StringBuilder code = new StringBuilder();
        //大写字母的ASCII值为65-90
        for (int i = 0; i < verifyCodeFigure; i++) {
            int j = (int) (Math.random() * 25) + 65;
            code.append((char) j);
        }
        return code.toString();
    }
}
